﻿using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Read.API.Command.ApplyCommand;
using MediatR;

namespace B.S.BaseData.Read.API.CommandHandler.ApplyHandler
{
    public class ApplyQueryCommandHandler : IRequestHandler<ApplyQueryCommand, APIResult<APIPaging<Apply>>>
    {
        private readonly IBaseRepository<Apply> _baseRepository;

        public ApplyQueryCommandHandler(IBaseRepository<Apply> baseRepository)
        {
            _baseRepository = baseRepository;
        }

        public async Task<APIResult<APIPaging<Apply>>> Handle(ApplyQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<Apply>> result = new APIResult<APIPaging<Apply>>();
            result.Code = APIEnum.Success;
            result.Msg = "查询成功";
            //((p.ApprovalStatusId == 1 && request.Importance == 1) || (p.ApprovalStatusId != 3 && request.Importance == 2))
            var list = _baseRepository.GetAll().Where(p=> p.ApplyPerson == request.Name || request.Importance>0);

            if (request.DatetimeBY != null)
            {
                list = list.Where(p => p.fristTime <= request.DatetimeBY && p.EndTime >= request.DatetimeBY);
            }
            if (request.ApprovalStatusId != null)
            {
                list = list.Where(p => p.ApprovalStatusId == request.ApprovalStatusId);
            }
            if (!string.IsNullOrEmpty(request.ApplyPerson))
            {
                list = list.Where(p => p.ApplyPerson == request.ApplyPerson);
            }
            APIPaging<Apply> paging = new APIPaging<Apply>();
            paging.TotalCount = list.Count();
            paging.PageCount = (int)Math.Ceiling(paging.TotalCount * 1.0 / request.PageSize);
            paging.Items = list.OrderByDescending(p=>p.ApplyId).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();

            result.Data = paging;
            return await Task.FromResult(result);
        }
    }
}
